<?php
namespace app\handler\wechat\ai;

use EasyWeChat\Kernel\Contracts\EventHandlerInterface;
use EasyWeChat\Kernel\Messages\Image;
use EasyWeChat\Kernel\Messages\Text;
use EasyWeChat\Kernel\Messages\Voice;

class SupervisorMessageHandler implements EventHandlerInterface
{
    use BaseMessageHandler;

    public function handle($message = null)
    {
        $wechat = $this->getApp();
        if ($wechat) {
            $sendMessage = $this->parseMessage($message);

            if ($sendMessage) {
                $openid = $this->getSupervisor();
                if ($openid) {
                    $wechat->customer_service
                        ->message($sendMessage)
                        ->to($openid)
                        ->send();
                }
            }
        }
        return null;
    }

    public function parseMessage($message)
    {
        $msgType = $message['MsgType'];
        $sendMessage = '';
        switch ($msgType) {
            case 'image' :
                $image = $message['MediaId'] ?? '';
                if ($image) {
                    $sendMessage = new Image($image);
                }
                break;
            case 'text' :
                $content = $message['Content'] ?? '';
                if ($content) {
                    $sendMessage = new Text($content);
                }
                break;
            case 'voice' :
                $voice = $message['MediaId'] ?? '';
                if ($voice) {
                    $sendMessage = new Voice($voice);
                }
                break;
            default :
                $sendMessage = '';
        }
        return $sendMessage;
    }

    public function getSupervisor()
    {
        $supervisor = config('wechat.to_openid');
        if ($supervisor) {
            return $supervisor;
        }
        return false;
    }
}